-- UIBlackForm
-- Created by dengc
-- 黑色遮罩的界面，用来屏蔽操作

UIBlackForm = class("UIBlackForm", function()
    return cc.Layer:create();
end);

function UIBlackForm.create(duration, callback, zOrder, tartgetNode, content, noHeroModle)
    return UIBlackForm.new(duration, callback, zOrder, tartgetNode, content, noHeroModle);
end

-- 构造函数
function UIBlackForm:ctor(duration, callback, zOrder, tartgetNode, content, noHeroModle)
    self:setName("UIBlackForm");
    local node = cc.CSLoader:createNode("layout/common/BlackForm1.csb");
    self:addChild(node);
    self.node = node;

    zOrder = zOrder or UIMgr.TOP_MENU_ZORDER + 100000;
    self:setLocalZOrder(zOrder);

    self.mask = findChildByName(node, "bt");

    self.effectNode = findChildByName(node, "CT/effect_node");

    -- 适配
    self:resize();

    -- 处于变身状态，创建变身状态的模型，否则创建普通模型
    if not noHeroModle then
        local shapeId = ShapeChangeM.getShapeChangeId();
        if type(shapeId) == "number" and shapeId ~= -1 then
            -- 获取当前的出战宠物
            local pet = ME.user:getActivePet();
            local userPetId = pet.classId;

            self:createShapeChangeModel(shapeId);
        else
            -- 创建英雄模型
            self:createHeroModel();
        end
    end
    local headImg = findChildByName(self.node, "CT/head_icon");
    headImg:setVisible(false);

    -- 创建怪物模型
    self:createMonsterModel(tartgetNode);

    -- 说话
    if content then
        self:showHeroTalk(content);
    end

    -- duration秒后自动关闭
    local function close()
        UIMgr.getCurrentScene():removeForm(self);

        if callback then
          callback();
        end
    end

    if duration ~= nil then
       performWithDelay(self, close, duration);
    end
end

-- 适配
function UIBlackForm:resize()
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;
    local node = self.node;

    local BT = node:getChildByName("bt");
    local BT2 = BT:getChildByName("bt_Copy");
    BT:loadTexture("images/ui/level/black_mask.png");
    BT2:loadTexture("images/ui/level/black_mask.png");
    BT:setContentSize(w, h);
    BT2:setContentSize(w, h);
    BT:setPosition(0, 0);
    BT2:setPosition(0, 0);

    AlignM.alignToTopCenter(node, "CT2");
    AlignM.alignToBottomCenter(node, "CT");

    local scale;
    if h / w > 1.5 then
        scale = w / (DESIGN_WIDTH);
    else
        -- 在宽高比小于等于1.5时（如iphone或ipad），需要略微比预定比例缩小些。 所以加了75像素
        scale = h / (DESIGN_HEIGHT + 75);
    end

    local effectNode = findChildByName(node, "effect_panel");
    effectNode:setPosition(w / 2, h / 2);
    effectNode:setScale(scale * DUNGEON_AJUST_SCALE);
end

-- 创建英雄模型
function UIBlackForm:createHeroModel()
    local headImg   = findChildByName(self.node, "CT/head_icon");
    local modelNode = findChildByName(self.node, "CT/model_node");

    -- 获取当前出战英雄
    local pet = ME.user:getActivePet();
    local classId = pet.classId;
    local petInfo = PetM.queryModel(pet:getModelId());

    local iconPath = getHeroIconPath(pet:getIcon());
    modelNode:removeAllChildren();
    self.modelNode = createHeroModel(pet:getModelId(), headImg, modelNode, petInfo["model_scale"], iconPath);
end

-- 创建变身后的英雄模型
function UIBlackForm:createShapeChangeModel(shapeId)
    local headImg   = findChildByName(self.node, "CT/head_icon");
    local modelNode = findChildByName(self.node, "CT/model_node");

    -- 查询变身信息
    local shapeInfo = ShapeChangeM.query(shapeId);

    -- 获取当前出战英雄
    local iconPath = getHeroLargeIconPath(shapeInfo["icon"]);
    local animation = shapeInfo["animation"];
    modelNode:removeAllChildren();
    self.modelNode = createShapeChangeMode(shapeId, headImg, animation, modelNode, shapeInfo["model_scale"], iconPath);
end

-- 创建怪物模型
function UIBlackForm:createMonsterModel(tartgetNode)
    if not tartgetNode then
        return;
    end

    local worldPos = tartgetNode:convertToWorldSpace(cc.p(0, 0));
    local monsterNode = cc.Node:create();

    if tartgetNode.gridData.monster then
        -- 普通怪物
        local classId = tartgetNode.gridData.monster.classId;
        local display = tartgetNode:createMonsterDisplay(classId);
        monsterNode:addChild(display);

        -- 需要停止动作
        if tartgetNode:getIsPause() then
            display:pauseActions();
        end

        local w = cc.Director:getInstance():getOpenGLView():getFrameSize().width;
        local h = cc.Director:getInstance():getOpenGLView():getFrameSize().height;
        local scale = math.min(w / DESIGN_WIDTH, h / DESIGN_HEIGHT);

        local grid = cc.Node:create();
        grid:addChild(monsterNode);

        local toPos = self:convertToNodeSpace(worldPos);
        grid:setPosition(toPos);
        grid:setScale(scale);

        if not tartgetNode.gridData.monster:isDead() then
            -- 有可能怪物已经死亡
            self:addChild(grid);
            self.grid = grid;
            self.monsterNode = monsterNode;
            self.gridPos = toPos;
            self.monsterDisplay = display;
        end

        return monsterNode;
    else
        local class = tartgetNode.gridData.class;
        local buildingInfo = BuildingBonusM.queryBuildingView(class);

        if not buildingInfo then
            return;
        end

         -- 建筑图标
        local iconPath = getLevelItemIconPath(buildingInfo["icon"]);

        local icon = ccui.ImageView:create(iconPath);

        local toPos = self:convertToNodeSpace(worldPos);
        monsterNode:setPosition(toPos);
        monsterNode:addChild(icon);
        self.buildingNode = monsterNode;
        self:addChild(monsterNode);
    end
end

-- 播放特效
function UIBlackForm:playEffect(parent, path, speed, callback, scale, offset)
    parent:setVisible(true);

    local effect, animAction = AnimationCacheM.createAnimationNodeAndAction(path);

    -- 设置速度
    if speed ~= nil then
        animAction:setTimeSpeed(speed);
    end

    -- 设置偏移
    if offset ~= nil then
        effect:setPosition(offset);
    end

    -- 设置缩放
    if scale ~= nil then
        effect:setScale(scale);
    end

    effect:runAction(animAction);
    animAction:gotoFrameAndPlay(1, 60, false);

    local callfunc = cc.CallFunc:create(function()
        parent:removeChild(effect);
        AnimationCacheM.freeAnimationNodeAndAction(path, effect, animAction);
        if callback ~= nil then
            callback();
        end
    end);

    effect:runAction(cc.Sequence:create(cc.DelayTime:create(0.5), callfunc));
    parent:addChild(effect);
end

-- 播放出战英雄虚影效果
function UIBlackForm:playActivePetShadowEffect(iconId)
    -- 把播放位置的坐标系转换到effectParent下面
    local effectParent = self.effectNode;
    local monsterNode = findChildByName(self.node, "CT/model_node");
    local worldPos = monsterNode:convertToWorldSpaceAR(cc.p(0, 0));
    local sourcePos = effectParent:convertToNodeSpace(worldPos);

    -- 预先放置图片
    local imageList = {};
    local function createImage(index)
        local image = ccui.ImageView:create();

        image:loadTexture(getHeroIconPath(iconId));
        image:setAnchorPoint(cc.p(0.5, 0.5));
        image:setScale(1.5);
        image:setOpacity(255 * 0.9 / index);
        effectParent:addChild(image);
        image:setPosition(sourcePos);
        table.insert(imageList, image);
    end

    createImage(1);
    createImage(2);

    -- 英雄位置出现一个虚影，放大
    local index = 1;
    local function playEffect()
        local image = imageList[index];

        local duration = 0.5;
        local scaleUp = cc.ScaleTo:create(duration, 1.8 * image:getScale());
        local fadeOut = cc.FadeTo:create(duration, 0);
        local moveUp = cc.MoveBy:create(duration, cc.p(0, 60));
        local callFunc = cc.CallFunc:create(function()
            image:removeFromParent();
        end);
        image:runAction(cc.Sequence:create(cc.Spawn:create(scaleUp, fadeOut, moveUp), callFunc));

        index = index + 1;
    end

    playEffect();
    performWithDelay(monsterNode, playEffect, 0.2);
end

-- 英雄发言
function UIBlackForm:showHeroTalk(content)
    local talk = findChildByName(self.node, "CT/talk");
    talk:setVisible(true);
    talk:setOpacity(255);

    local text = findChildByName(self.node, "CT/talk/text");
    TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    text:setString(content);

    talk:stopAllActions();
    talk:runAction(cc.Sequence:create(cc.DelayTime:create(0.5), cc.FadeOut:create(2)));
end

-- 切换英雄动作
function UIBlackForm:switchHeroAction(actionType)
    local heroDisplay = findChildByName(self.modelNode, "HeroDisplay");
    if not heroDisplay then
        return;
    end

    heroDisplay:switchAction(actionType);
end

-- 座钟特效
function UIBlackForm:playDeskClockEffect()
    if self.buildingNode then

        local function callback()
            EventMgr.fire(event.PLAYER_MOVE);
            UIMgr.getCurrentScene():removeFormByName("UIBlackForm");
        end

        local worldPos = self.modelNode:convertToWorldSpace(cc.p(0, 0));
        local toPos = self:convertToNodeSpace(worldPos);
        deskclockTrapEffect(self.buildingNode, toPos, self, callback);
    end
end

-- 播放
function UIBlackForm:playBoodyTestbedFailEffect()
    if self.buildingNode then

        local function callback()
            EventMgr.fire(event.PLAYER_MOVE);
            UIMgr.getCurrentScene():removeFormByName("UIBlackForm");
        end

        performWithDelay(self, callback, 1);

        -- 爆炸光效
        playShakeEffect(self.buildingNode, 0.03, 4, 4);
        playEffect(self.buildingNode, 1233, 0, 20);

        local function  heroEffect()
            -- 使用默认的死亡动画
            local path = "animation/die_bomb.csb";
            local effect, animAction = AnimationCacheM.createAnimationNodeAndAction(path);
            effect:runAction(animAction);
            self.modelNode:addChild(effect);
            animAction:gotoFrameAndPlay(0, 14, false);

            local function callFunc()
                AnimationCacheM.freeAnimationNodeAndAction(path, effect, animAction);
            end

            performWithDelay(self.modelNode, callFunc, 0.3);
        end

        performWithDelay(self, heroEffect, 0.5);
    end
end

-- 播放
function UIBlackForm:playBreakSealFailEffect()
    if self.buildingNode then

        local function callback()
            EventMgr.fire(event.PLAYER_MOVE);
            UIMgr.getCurrentScene():removeFormByName("UIBlackForm");
        end

        performWithDelay(self, callback, 1);

        -- 爆炸光效
        playEffect(self.buildingNode, 54, 0, 20);

        local function  heroEffect()
            -- body
            playEffect(self.modelNode, 51, 0, 20);
        end

        performWithDelay(self, heroEffect, 0.5);
    end
end